import React, { useState, useRef } from "react"
import { useAppDispatch, useAppSelector } from "~store"
import { Table, Space, Tag, Button, Modal, ImgDefault, message, Icon, Badge } from '@bytedance/mona-ui';
import type { ColumnProps } from '@bytedance/mona-ui/es/components/table';
import AutoSetActBox from './autoSetActBox'
import moment from 'moment'
import { store } from "~store"

function AutoListContent() {

    const [autoActivityBoxStatus, setAutoActivityBoxStatus] = useState(false)
    const [copyActItemOne, setCopyActItemOne] = useState<any>({})
    const [lookActGoodsStatus, setLookActGoodsStatus] = useState(false)
    const [lockGoodsList, setLockGoodsList] = useState<any>([])
    const [lockAutoLogs, setLockAutoLogs] = useState<any>([])
    const [lockAutoLogBoxStatus, setLockAutoLogBoxStatus] = useState(false)

    type AutoRefsType = {
        // 子组件暴露给父组件的方法

        getData: any;
        // setAddpritVstatus1: () => void;
    };
    const autoRefs = useRef<AutoRefsType>(null);


    const autoSetActivityList = useAppSelector(
        (state) => state.autoActivity.autoSetActivityList
    )
    const autoSetLogsList = useAppSelector(
        (state) => state.autoActivity.autoSetLogsList
    )
    // console.log('创建日志', autoSetLogsList)
    interface ITableData {
        index: number;
        name: string;
        year: number;
        addr: string;
        school: string;
        intro: string;
        birth: string;
    }
    const columns: ColumnProps<ITableData>[] = [{
        title: '序号',
        key: '0',
        dataIndex: 'id',
        render: (text, record, index) => index + 1
    },
    {
        title: '原活动名称',
        key: 'title',
        render: (text: any, record: any) => {
            return <Space direction="vertical" size={2}>
                <div className="tit">
                    {record.addLtaLpConfig.title}
                </div>
                <Tag bordered color={
                    (record.addLtaLpConfig.business_code === 'LimitTime' || record.addLtaLpConfig.business_code === '') ? '#6C26FD' : record.addLtaLpConfig.business_code === 'LimitQuantity' ? '#2B71FF' : '#252931'
                } transparentBg>{(record.addLtaLpConfig.business_code === 'LimitTime' || record.addLtaLpConfig.business_code === '') ? '限时抢购' : record.addLtaLpConfig.business_code === 'LimitQuantity' ? '限量抢购' : record.addLtaLpConfig.business_code === 'OrdinaryTimeBuy' ? '普通降价促销' : ''}</Tag>
            </Space>
        }
    },
    // {
    //     title: '预热开始时间',
    //     // dataIndex: 'campaign_status',
    //     key: 'campaign_status',
    //     render: (text: any, record: any) => {
    //         return record.addLtaLpConfig.pre_begin_time === record.addLtaLpConfig.begin_time ? '-' : record.addLtaLpConfig.pre_begin_time
    //     }
    // },
    {
        title: '优惠类型',
        // dataIndex: 'start_time',
        key: 'shop_stype',
        render: (text: any, record: any) => {

            return <div>
                {record.addLtaLpConfig.shop_stype == '1' ? '一口价' : record.addLtaLpConfig.shop_stype == '2' ? '直降' : record.addLtaLpConfig.shop_stype == '3' ? '打折' : ''}
            </div>
        }
    },
    {
        title: '状态',
        // dataIndex: 'status',
        key: 'status',
        render: (text: any, record: any) => {
            return (record.autoSetConfig.useNumber > 0 && record.status != 1) ? <Tag.Status type="success">
                已经创建{record.autoSetConfig.useNumber}个活动
            </Tag.Status> : record.status == 1 ? <Tag.Status>正在进行中</Tag.Status> : <Tag.Status type="warn">等待创建</Tag.Status>
        }
    },
    {
        title: '自动续期数',
        // dataIndex: 'start_time',
        key: 'autoNumber',
        render: (text: any, record: any) => {

            return record.autoSetConfig.autoNumber + '次'
        }
    },
    {
        title: '活动商品',
        // dataIndex: 'start_time',
        key: 'sendNumber',
        render: (text: any, record: any) => {
            // console.log('record', record)
            return <Button type="link" onClick={() => {
                setCopyActItemOne(record)
                setLockGoodsList(record.addLtaLpConfig.promotion_goods)
                setLookActGoodsStatus(true)
            }}>查看活动商品</Button>
        }
    },
    {
        title: '活动时长',
        // dataIndex: 'start_time',
        key: 'actTimeType',
        render: (text: any, record: any) => {
            const { actTimeType, timeTypRedou, hoursLen, minutesLen } = record.autoSetConfig
            const { begin_time, end_time } = record.addLtaLpConfig
            if (actTimeType == 1) {
                const start = moment(begin_time);
                const end = moment(end_time);
                const duration = moment.duration(end.diff(start));

                // 获取几天、几小时、几分钟和几秒
                const days = duration.days();
                const hours = duration.hours();
                const minutes = duration.minutes();
                const seconds = duration.seconds();


                return `${days ? days + '天' : ''} ${hours ? hours + '小时' : ''} ${minutes ? minutes + '分' : ''} ${seconds ? seconds + '秒' : ''}`
                // return `${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`
            }
            if (timeTypRedou == 1) {
                return hoursLen + '小时'
            }
            return minutesLen + '分钟'
        }
    },
    // {
    //     title: '删除原活动',
    //     // dataIndex: 'start_time',
    //     key: 'deleteOldActStatus',
    //     render: (text: any, record: any) => {
    //         return record.autoSetConfig.deleteOldActStatus ? '是' : '否'
    //     }
    // }, 
    {
        title: '优惠力度不匹配',
        // dataIndex: 'start_time',
        key: 'notIsPre',
        render: (text: any, record: any) => {
            return record.autoSetConfig.notIsPre == 1 ? '适配最低价格' : '跳过不符合商品'
        }
    },
    {
        title: '自定义活动前缀',
        // dataIndex: 'start_time',
        key: 'befoTitle',
        render: (text: any, record: any) => {
            return record.autoSetConfig.befoTitle || ''
        }
    },
    {
        title: '创建时间',
        dataIndex: 'updata_time',
        key: 'updata_time'
    },

    {
        title: '操作',
        key: 'action',
        render: (text: any, record: any) => {
            return <Space>
                <Button
                    type="link"
                    danger
                    style={{
                        color: 'red'
                    }}
                    disabled={record.status == 1}
                    onClick={() => {
                        if (record.status == 1) return
                        window.postMessage({
                            type: 'dly_activity_modole',
                            dly_method: 'delete',
                            shop_id: store.getState().jinritemaiShops.userShopId,
                            id: record.id
                        })
                    }}>删除</Button>
                <Button type="link" disabled={record.status == 1} onClick={() => {
                    setCopyActItemOne(record)
                    setAutoActivityBoxStatus(true)
                }}>编辑</Button>
                <Badge count={autoSetLogsList.filter((item: any) => item.activit_id == record.id).length}>
                    <Button type="link" onClick={() => {
                        // setCopyActItemOne(record)
                        const getUterlitser = autoSetLogsList.filter((item: any) => item.activit_id == record.id)
                        setLockAutoLogs(getUterlitser)
                        setLockAutoLogBoxStatus(true)
                    }}>创建日志</Button>
                </Badge>

            </Space>

        }
    }
    ]
    const goodsColumns = [
        // {
        //     title: '商品图片',
        //     // dataIndex: 'product_id',
        //     key: 'image',
        //     render: (text: any, record: any) => {
        //         return <ImgDefault src={record.cover} style={{ width: '50px', height: '50px' }} alt="" />
        //     }
        // },
        {
            title: '商品信息',
            // dataIndex: 'product_id',
            key: 'product_info',
            width: 300,
            render: (text: any, record: any) => {
                return (
                    <Space direction="vertical">
                        <Space>
                            <ImgDefault
                                imgSrc={record.cover}
                                mask={false}
                                width={60}
                                height={60}></ImgDefault>
                            <Space direction="vertical" size={4}>
                                <div
                                    className="title"
                                    style={{
                                        fontSize: 12,
                                        color: "#252931"
                                    }}>
                                    {record.title}
                                </div>
                                <div
                                    className="isduer"
                                    style={{
                                        color: "#898b8f",
                                        fontSize: 12
                                    }}>
                                    ID:{record.product_id}
                                    <Icon
                                        type="CopyIcon"
                                        className="copyiconitem"
                                        style={{
                                            marginLeft: 5,
                                            cursor: "pointer"
                                            // opacity: 0,
                                            // ':hover': {
                                            //     color: '#1966FF'
                                            // }
                                        }}
                                        onClick={() => copyToClipboard(record.product_id)}
                                    />
                                </div>
                            </Space>
                        </Space>

                    </Space>
                )
                // return <div>
                //     <div>{record.title}</div>
                //     <div>商品ID：{record.product_id}</div>
                // </div>
            }
        },
        // {
        //     title: '商品名',
        //     dataIndex: 'title',
        //     key: 'title'
        // }, 
        {
            title: '已创建数',
            dataIndex: 'useNumber',
            key: 'useNumber'
        },
        {
            title: '总次数',
            dataIndex: 'autoNumber',
            key: 'autoNumber'
        },
        // {
        //     title: '操作',
        //     key: 'action',
        //     render: (record) => {
        //         return <Space>
        //             <Button
        //                 type="link"
        //                 danger
        //                 style={{
        //                     color: 'red'
        //                 }}
        //                 onClick={() => {
        //                     console.log('record', record, autoSetActivityList)
        //                     window.postMessage({
        //                         type: 'dly_activity_modole',
        //                         dly_method: 'delete_prodect',
        //                         product_id: record.product_id,
        //                         id: copyActItemOne.id,
        //                         shop_id: store.getState().jinritemaiShops.userShopId,
        //                     })
        //                 }}>删除</Button>
        //             {/* <Button type="link" onClick={() => {
        //                 setCopyActItemOne(record)
        //                 setAutoActivityBoxStatus(true)
        //             }}>编辑</Button> */}
        //         </Space>
        //     }
        // }
    ]
    function copyToClipboard(text) {
        navigator.clipboard
            .writeText(text)
            .then(function () {
                message.success("复制成功")
            })
            .catch(function (err) {
                message.error("复制失败")
            })
    }

    const autoLogsColumns = [{
        title: '活动名称',
        // dataIndex: 'title',
        key: 'title',
        render: (text, record) => {

            return <Space direction="vertical" size={2}>
                <div className="tit">
                    {record.data.title}
                </div>
                <Tag bordered color={
                    (record.data.business_code === 'LimitTime' || record.data.business_code === '') ? '#6C26FD' : record.data.business_code === 'LimitQuantity' ? '#2B71FF' : '#252931'
                } transparentBg>{(record.data.business_code === 'LimitTime' || record.data.business_code === '') ? '限时抢购' : record.data.business_code === 'LimitQuantity' ? '限量抢购' : record.data.business_code === 'OrdinaryTimeBuy' ? '普通降价促销' : ''}</Tag>
            </Space>
            // record.data.title
        }
    },
    {
        title: '优惠类型',
        // dataIndex: 'start_time',
        key: 'shop_stype',
        render: (text: any, record: any) => {
            return <div>
                {record.data.shop_stype == '1' ? '一口价' : record.data.shop_stype == '2' ? '直降' : record.data.shop_stype == '3' ? '打折' : ''}
            </div>
        }
    },
    {
        title: '活动时间',
        // dataIndex: 'activity_id',
        key: 'activity_time',
        render: (text, record) => {
            return <Space direction="vertical">
                <span>{record.data.begin_time}</span>
                <span>{record.data.end_time}</span>
            </Space>
        }
    },
    {
        title: '活动商品',
        key: 'activity_product',
        render: (text, record) => {
            return <Space>
                显示活动商品列表
            </Space>
        }
    },
    {
        title: '创建时间',
        key: 'tīme',
        dataIndex: 'time'
    },
    {
        title: 'JSON',
        key: 'json',
        render: (text, record) => {
            return <Button type="link" onClick={() => {
                Modal.confirm({
                    title: 'JSON',
                    content: JSON.stringify(record.res),
                    okText: '复制JSON',
                    cancelText: '取消',
                    maskClosable: true,
                    style: {
                        height: '300px',
                        width: '600px'
                    },
                    onOk() {
                        navigator.clipboard.writeText(JSON.stringify(record.data))
                            .then(function () {
                                message.success('复制成功')
                            })
                            .catch(function (err) {
                                message.error('复制失败')
                            })
                    }
                    // onOk() {
                    //     navigator.clipboard.writeText(JSON.stringify(record.data))
                    //         .then(function ()
                })
            }}>查看</Button>
        }
    }
    ]
    return <>
        添加任务后会自动运行， 若想保证任务对应商品的活动按时创建请保证浏览器不关闭，同时及时检查商品库存是否充足
        <Table
            title={() => (
                <Space>
                    <Button type="primary" size="mini" onClick={() => {
                        // console.log('clierall')

                        window.postMessage({
                            type: 'dly_activity_modole',
                            dly_method: 'clear',
                            shop_id: store.getState().jinritemaiShops.userShopId,

                        })
                    }}>删除全部任务</Button>
                </Space>
            )}
            columns={columns} rowKey="index" dataSource={autoSetActivityList} />
        <Modal
            title="编辑活动自动续期"
            visible={autoActivityBoxStatus}
            onCancel={() => setAutoActivityBoxStatus(false)}
            onOk={() => {
                if (autoRefs.current) {
                    const { addLtaLpConfig, autoSetConfig } = autoRefs.current?.getData
                    // console.log('getDatas', getDatas)

                    window.postMessage({
                        type: 'dly_activity_modole',
                        dly_method: 'updata',
                        shop_id: store.getState().jinritemaiShops.userShopId,
                        data: {
                            addLtaLpConfig,
                            autoSetConfig,
                            id: copyActItemOne.id,
                            updata_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                        }
                    })
                }
                setAutoActivityBoxStatus(false)
            }}
            destroyOnClose={true}
        > <AutoSetActBox copyData={copyActItemOne.addLtaLpConfig} autoSetConfigData={copyActItemOne.autoSetConfig} ref={autoRefs} />
        </Modal>
        <Modal
            title="查看活动商品"
            visible={lookActGoodsStatus}
            footer={null}
            onCancel={() => setLookActGoodsStatus(false)}
            onOk={() => setLookActGoodsStatus(false)}
        >
            <Table columns={goodsColumns} dataSource={lockGoodsList}></Table>
        </Modal>
        <Modal
            title="创建日志"
            visible={lockAutoLogBoxStatus}
            footer={null}
            onCancel={() => setLockAutoLogBoxStatus(false)}
            onOk={() => setLockAutoLogBoxStatus(false)}
            width={1000}
        >
            <Table columns={autoLogsColumns} dataSource={lockAutoLogs}></Table>
        </Modal>
    </>
}

export default AutoListContent